MediaPlayer
The MediaPlayer API allows you to interact with the Now Playing Center, manage Now Playing Info, and respond to remote control events. Below is a comprehensive guide on its usage, including best practices and examples.
Getting Started
The MediaPlayer API provides control over media playback information and remote command handling. To get started:
- Set the
nowPlayingInfoto display current media information. - Configure available commands using
setAvailableCommands(). - Register a
commandHandlerto respond to remote events.
API Reference
NowPlayingInfo
The nowPlayingInfo object displays metadata about the currently playing media. Set it to null to clear the Now Playing Info Center.
Properties:
title:string(Required)- The title of the media item.
artist:string(Optional)- The artist or performer of the media item.
albumTitle:string(Optional)- The album title of the media item.
artwork:UIImage(Optional)- An image representing the media item.
mediaType:MediaType(Optional)- Defaults to
audio.
- Defaults to
playbackRate:number(Optional)- Defaults to
0. Indicates the current playback rate.
- Defaults to
elapsedPlaybackTime:DurationInSeconds(Optional)- Defaults to
0. The current playback time.
- Defaults to
playbackDuration:DurationInSeconds(Optional)- Defaults to
0. The total duration of the media.
- Defaults to
Playback State
The playbackState property indicates the app's current playback state:
unknown: Default state when playback status is undefined.playing: Media is actively playing.paused: Media playback is paused.stopped: Playback has stopped.interrupted: Playback is interrupted by an external event.
Commands and Event Handlers
setAvailableCommands(commands: MediaPlayerRemoteCommand[])
Specifies which remote commands are enabled for user interaction.
Example:
commandHandler
A callback to handle remote commands. Register this function to process commands like play, pause, or seekBackward.
Example:
Supported Commands:
play,pause,stop,nextTrack,previousTrackseekBackward,seekForward,skipBackward,skipForwardrating,like,dislike,bookmarkchangeRepeatMode,changeShuffleModeenableLanguageOption,disableLanguageOption
Common Use Cases
Display Now Playing Info
Respond to Playback Commands
Handle Custom Events
Best Practices
- Keep Metadata Up-to-Date: Update
nowPlayingInfoas playback changes. - Handle All Relevant Commands: Ensure user interactions like skipping or seeking are supported.
- Resource Management: Clear
nowPlayingInfowhen playback stops to avoid stale information. - Test with External Devices: Use remote controls like headphones or car systems to validate command handling.
- Provide Feedback: Inform users of successful or failed actions in response to commands.
Full Example
Below is a complete implementation of MediaPlayer:
